require 'omniauth-oauth2'
require 'multi_json'

module OmniAuth
  module Strategies
    class RunKeepersc < OmniAuth::Strategies::OAuth2
      option :client_options, {
        :site             => 'http://api.runkeeper.com',
        :authorize_url    => 'https://runkeeper.com/apps/authorize',
        :token_url        => 'https://runkeeper.com/apps/token'
      }

      uid { raw_info['id'] }

      info do
        {
          :name           => raw_info['name'],
          :location       => raw_info['location'],
          :athlete_type   => raw_info['athlete_type'],
          :gender         => raw_info['gender'],
          :image          => raw_info['small_picture'],
          :urls           => { 'RunKeepersc' => raw_info['profile'] }
        }
      end

      extra do
        { :raw_info => raw_info }
      end

      def raw_info
        @raw_info ||= begin
          user = MultiJson.decode(access_token.get('/user').body)
          profile = MultiJson.decode(access_token.get(user['profile']).body)    
          { 'id' => user['userID'] }.merge(profile)
        end
      end

    end
  end
end

OmniAuth.config.add_camelization 'runkeepersc', 'RunKeepersc'